import request from '@/utils/request'
import type {
  User,
  CreateUserRequest,
  UpdateUserRequest,
  Role,
  CreateRoleRequest,
  UpdateRoleRequest,
  Permission,
  CreatePermissionRequest,
  UpdatePermissionRequest,
  SystemConfig,
  CreateSystemConfigRequest,
  UpdateSystemConfigRequest,
  OperationLog,
  SystemStats,
  PaginationParams,
  PaginationResponse,
  ApiResponse,
  LoginRequest,
  LoginResponse,
  RefreshTokenResponse
} from '@/types'

// 认证API
export const authApi = {
  // 用户登录
  login: (data: LoginRequest) =>
    request.post<LoginResponse>('/admin/auth/login', data),

  // 用户登出
  logout: () =>
    request.post('/admin/auth/logout'),

  // 刷新令牌
  refreshToken: () =>
    request.post<RefreshTokenResponse>('/admin/auth/refresh'),

  // 获取用户信息
  getProfile: () =>
    request.get<User>('/admin/auth/profile')
}

// 用户管理API
export const userApi = {
  // 获取用户列表
  getUsers: (params?: PaginationParams & { status?: string }) =>
    request.get<PaginationResponse<User>>('/admin/users', { params }),

  // 获取用户详情
  getUser: (id: number) =>
    request.get<{ user: User }>(`/admin/users/${id}`),

  // 创建用户
  createUser: (data: CreateUserRequest) =>
    request.post<{ user: User }>('/admin/users', data),

  // 更新用户
  updateUser: (id: number, data: UpdateUserRequest) =>
    request.put<{ user: User }>(`/admin/users/${id}`, data),

  // 删除用户
  deleteUser: (id: number) =>
    request.delete(`/admin/users/${id}`),

  // 重置用户密码
  resetPassword: (id: number) =>
    request.post(`/admin/users/${id}/reset-password`),

  // 更新用户状态
  updateStatus: (id: number, status: string) =>
    request.patch(`/admin/users/${id}/status`, { status }),

  // 启用用户
  enableUser: (id: number) =>
    request.patch(`/admin/users/${id}/enable`),

  // 禁用用户
  disableUser: (id: number) =>
    request.patch(`/admin/users/${id}/disable`),

  // 获取用户统计
  getStats: () =>
    request.get<SystemStats>('/admin/users/stats'),

  // 上传头像
  uploadAvatar: (file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<User>('/admin/users/upload-avatar', formData)
  },

  // 管理员为指定用户上传头像
  uploadUserAvatar: (userId: number, file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<User>(`/admin/users/${userId}/avatar`, formData)
  },

  // 更新个人资料
  updateProfile: (data: { realName?: string; email?: string; phone?: string }) =>
    request.put<User>('/admin/users/update-profile', data),

  // 修改密码
  changePassword: (data: { currentPassword: string; newPassword: string }) =>
    request.post('/admin/users/change-password', data)
}

// 角色管理API
export const roleApi = {
  // 获取角色列表
  getRoles: (params?: PaginationParams & { status?: string }) =>
    request.get<PaginationResponse<Role>>('/admin/roles', { params }),

  // 获取角色详情
  getRole: (id: number) =>
    request.get<{ role: Role }>(`/admin/roles/${id}`),

  // 创建角色
  createRole: (data: CreateRoleRequest) =>
    request.post<{ role: Role }>('/admin/roles', data),

  // 更新角色
  updateRole: (id: number, data: UpdateRoleRequest) =>
    request.put<{ role: Role }>(`/admin/roles/${id}`, data),

  // 删除角色
  deleteRole: (id: number) =>
    request.delete(`/admin/roles/${id}`),

  // 更新角色状态
  updateStatus: (id: number, status: string) =>
    request.patch(`/admin/roles/${id}/status`, { status }),

  // 获取角色权限
  getRolePermissions: (id: number) =>
    request.get<{ permissions: Permission[] }>(`/admin/roles/${id}/permissions`),

  // 更新角色权限
  updateRolePermissions: (id: number, permissionIds: number[]) =>
    request.put(`/admin/roles/${id}/permissions`, { permissionIds }),

  // 获取角色用户
  getRoleUsers: (id: number) =>
    request.get<{ users: User[] }>(`/admin/roles/${id}/users`),

  // 分配权限
  assignPermissions: (id: number, permissionIds: number[]) =>
    request.put(`/admin/roles/${id}/permissions`, { permissionIds })
}

// 权限管理API
export const permissionApi = {
  // 获取权限列表
  getPermissions: (params?: PaginationParams & { module?: string }) =>
    request.get<PaginationResponse<Permission>>('/admin/permissions', { params }),

  // 获取权限详情
  getPermission: (id: number) =>
    request.get<{ permission: Permission }>(`/admin/permissions/${id}`),

  // 创建权限
  createPermission: (data: CreatePermissionRequest) =>
    request.post<{ permission: Permission }>('/admin/permissions', data),

  // 更新权限
  updatePermission: (id: number, data: UpdatePermissionRequest) =>
    request.put<{ permission: Permission }>(`/admin/permissions/${id}`, data),

  // 删除权限
  deletePermission: (id: number) =>
    request.delete(`/admin/permissions/${id}`),

  // 获取权限树
  getPermissionTree: () =>
    request.get<{ permissions: Permission[] }>('/admin/permissions/tree'),

  // 获取权限模块
  getPermissionModules: () =>
    request.get<{ modules: string[] }>('/admin/permissions/modules'),

  // 获取权限树
  getTree: () =>
    request.get<{ tree: any[] }>('/admin/permissions/tree'),

  // 获取权限模块统计
  getModules: () =>
    request.get<{ modules: Array<{ module: string, count: number }> }>('/admin/permissions/modules'),

  // 批量创建权限
  batchCreate: (permissions: CreatePermissionRequest[]) =>
    request.post<{ results: Permission[], errors: any[] }>('/admin/permissions/batch', { permissions })
}

// 系统管理API
export const systemApi = {
  // 系统配置
  config: {
    // 获取配置列表
    getList: (params?: PaginationParams & { type?: string }) =>
      request.get<PaginationResponse<SystemConfig>>('/admin/system/configs', { params }),

    // 获取配置详情
    getById: (id: number) =>
      request.get<{ config: SystemConfig }>(`/admin/system/configs/${id}`),

    // 创建配置
    create: (data: CreateSystemConfigRequest) =>
      request.post<{ config: SystemConfig }>('/admin/system/configs', data),

    // 更新配置
    update: (id: number, data: UpdateSystemConfigRequest) =>
      request.put<{ config: SystemConfig }>(`/admin/system/configs/${id}`, data),

    // 删除配置
    delete: (id: number) =>
      request.delete(`/admin/system/configs/${id}`),

    // 批量更新配置
    batchUpdate: (configs: UpdateSystemConfigRequest[]) =>
      request.put('/admin/system/configs/batch', { configs })
  },

  // 系统统计
  stats: () =>
    request.get<SystemStats>('/admin/system/stats')
}

// 日志管理API
export const logApi = {
  // 获取日志列表
  getList: (params?: PaginationParams & { 
    userId?: number, 
    action?: string, 
    resource?: string,
    startDate?: string, 
    endDate?: string,
    search?: string,
    ipAddress?: string,
    sortBy?: string,
    sortOrder?: string
  }) =>
    request.get<PaginationResponse<OperationLog>>('/admin/logs', { params }),

  // 获取日志详情
  getById: (id: number) =>
    request.get<OperationLog>(`/admin/logs/${id}`),

  // 清空日志
  clear: (beforeDate?: string) =>
    request.delete('/admin/logs/clear', { data: { beforeDate } }),

  // 获取日志统计
  getStats: (params?: { startDate?: string, endDate?: string }) =>
    request.get<any>('/admin/logs/stats', { params }),

  // 获取日志分析
  getAnalytics: (params?: { startDate?: string, endDate?: string }) =>
    request.get<any>('/admin/logs/analytics', { params }),

  // 导出日志
  export: (params?: { 
    format?: string, 
    startDate?: string, 
    endDate?: string,
    userId?: number,
    action?: string,
    resource?: string,
    search?: string
  }) =>
    request.get<any>('/admin/logs/export', { params })
} 